package com.andiary.common.note;


import java.util.ArrayList;

import com.andiary.common.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.telephony.gsm.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class SendMail extends Activity implements TextWatcher{
	
	private AutoCompleteTextView contact;
    private ImageButton btnNote;
    private ImageButton btnInfo;
    private EditText ad;
    private TextView adcontact;
    private Button btnSend; 
	private String mailnumber;
	private int nameColumnIndex;
	private Cursor addr;

	 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);


        	// mDbHelper = new NotesDbAdapter(this);
             //mDbHelper.open();
         
        setContentView(R.layout.mailcontact);
        
        btnNote = (ImageButton) findViewById (R.id.day);
        btnNote.setOnClickListener(btnNoteListener);

        btnInfo = (ImageButton) findViewById (R.id.info);
        btnInfo.setOnClickListener(btnInfoListener);
        
        btnSend = (Button) findViewById(R.id.send);
        btnSend.setOnClickListener(btnSendListener);
        
        
        contact= (AutoCompleteTextView) findViewById (R.id.contact);
        ad=(EditText) findViewById(R.id.mail); 
        adcontact= (TextView) findViewById (R.id.adcontact);        
     	  
 		ad.requestFocus();
	     
	        ContentResolver content = getContentResolver();
	        
	        
	     Cursor cursor = content.query(
	    		 Contacts.People.CONTENT_URI,PEOPLE_PROJECTION,null, null,
	    		 Contacts.People.NAME);
//	      ContactListAdapter adapter = new ContactListAdapter(this, cursor);

 		
     	contact.addTextChangedListener(this);  	
     	contact.setAdapter(new ContactListAdapter(this,addr)); 
    	}
public void onTextChanged(CharSequence s, int start, int before, 
            int count) { 
	String name= s.toString();
	Cursor	nameCursor = managedQuery(Contacts.ContactMethods.CONTENT_EMAIL_URI, new String[] {
			Contacts.ContactMethods._ID,Contacts.ContactMethods.DATA, 
			Contacts.ContactMethods.NAME,
		}, null, null, null);

if (nameCursor.moveToFirst()) {		
 		
 		do { 
			nameColumnIndex = nameCursor.getInt(nameCursor.getColumnIndex(Contacts.ContactMethods.NAME));
			
			if (name.equals(nameCursor.getString(nameCursor.getColumnIndex(Contacts.ContactMethods.NAME)))) {
				
								int iMail = nameCursor
										.getColumnIndex(Contacts.ContactMethods.DATA);
									
					mailnumber=nameCursor.getString(nameCursor.getColumnIndex(Contacts.ContactMethods.DATA));	
					ad.setText(mailnumber);
					btnSend.requestFocus();
								
						}
					
 		}	while (nameCursor.moveToNext());
 		
 	}
	
} 

public void beforeTextChanged(CharSequence s, int start, 
                int count, int after) { 
// needed for interface, but not used 
} 

public void afterTextChanged(Editable s) { 
// needed for interface, but not used 
} 
   
    public static class ContactListAdapter extends CursorAdapter implements Filterable {
        public ContactListAdapter(Context context, Cursor c) {
            super(context, c);
            mContent = context.getContentResolver();
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
        	
            final LayoutInflater inflater = LayoutInflater.from(context);
            final TextView view = (TextView) inflater.inflate(
                    android.R.layout.simple_dropdown_item_1line, parent, false);
            view.setText(cursor.getString(1));
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ((TextView) view).setText(cursor.getString(1));
        }

        @Override
        public String convertToString(Cursor cursor) {
            return cursor.getString(1);
        }

        @Override
        public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
            if (getFilterQueryProvider() != null) {
                return getFilterQueryProvider().runQuery(constraint);
            }

            StringBuilder buffer = null;
            String[] args = null;
            if (constraint != null) {
                buffer = new StringBuilder();
                buffer.append("UPPER(");
                buffer.append(Contacts.People.NAME);
                buffer.append(") GLOB ?");
                args = new String[] { constraint.toString().toUpperCase() + "*" };
            }

            return mContent.query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION,
                    buffer == null ? null : buffer.toString(), args,
                    		Contacts.People.NAME);
        }

        private ContentResolver mContent;        
    }

    private static final String[] PEOPLE_PROJECTION = new String[] {
    	Contacts.People._ID,
    	Contacts.People.NAME,
    
    };
    private Button.OnClickListener btnNoteListener= new Button.OnClickListener() {

		public void onClick(View view) {               
			setResult(RESULT_OK);
			finish();
		}
  
	};
	
    private Button.OnClickListener btnInfoListener= new Button.OnClickListener() {

    	public void onClick(View view) {
	
        //	Intent info = new Intent(SendSMS.this,.Info.class);
    	  //  startActivity(info);
    	//	finish();
    	
    	}
  
    };   
    private Button.OnClickListener btnSendListener= new Button.OnClickListener() {

    	public void onClick(View view) {
    		
    		mailnumber=ad.getText().toString();
  	      
      		new AlertDialog.Builder(SendMail.this)            	
              
              .setMessage("Sent a Mail to  "+"\n"+mailnumber+" ?")
          
              .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                     
              String titlemail="t";   
    		  String textmail= "r";
    		 

    			    String destAddr =  mailnumber;

    			    try {
    			    	final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    			    	emailIntent .setType("plain/text");
    			    	emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{destAddr});
    			    	emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, titlemail);
    			    	emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, textmail);
    			    	startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    			     
    			     Log.i("TEST", "message envoyer a l'adresse: "+destAddr);
    			     
    	  			 Toast.makeText(SendMail.this, "Your message have been sent", Toast.LENGTH_SHORT).show();
    	  			 
    			    } catch (Exception e) {
    			    	
    			      Log.i("TEST", e.toString());
    			      
    			      Toast.makeText(SendMail.this, "type a correct mail number", Toast.LENGTH_LONG).show();
    			    }
    			    		ad.requestFocus();
                  }
                  })
                  
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int whichButton) {
                      	  	ad.requestFocus();
                       }
                   })
                   .show();
    			}
    	};
}